﻿using System.Web.UI.WebControls;
using ApplicationGenerator.DataAccess;
using ApplicationGenerator.CommonModule;

namespace ApplicationGenerator.GeneratorMenu.BusinessLogic
{
    /// <summary>
    /// Klasa zwracająca stworzoną kontrolkę webową menu
    /// </summary>
    public class MenuConfiguration
    {

        public Menu GetMenu(string userName)
        {
            Menu menu = new Menu();
            ApplicationMenu applicationMenu = GetApplicationMenu();

            foreach (var menuElement in applicationMenu.Items)
            {
                if (!UserManager.UserBelongToRoles(userName, menuElement.Roles))
                {
                    continue;
                }

                MenuItem newItem = new MenuItem();
                newItem.Text = menuElement.Text;
                newItem.NavigateUrl = menuElement.Url;

                menu.Items.Add(newItem);
                InitializeMenu(menuElement, newItem);
            }

            return menu;
        }

        private void InitializeMenu(ApplicationMenuBase menuBase, MenuItem baseItem)
        {
            foreach (var menuElemnt in menuBase.Items)
            {
                MenuItem newItem = new MenuItem();
                newItem.Text = menuElemnt.Text;
                newItem.NavigateUrl = menuElemnt.Url;

                baseItem.ChildItems.Add(newItem);
                InitializeMenu(menuElemnt, newItem);
            }
        }

        private ApplicationMenu GetApplicationMenu()
        {
            return (ApplicationMenu)Serializer.Deserialize(Policy.Menu, "menu");
        }

    }
}
